var app = getApp()
import Toast from 'tdesign-miniprogram/toast/index';
var util = require('../../../utils/util.js')

Page({
  data: {
    userInfo: {
      avatarurl: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.nDJn6jO-bh7AzEOdcLiiCQAAAA?w=177&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7',
      nickname: '',
      gender: 0,
      telnum: '',
    },
    showUnbindConfirm: false,
    genders: [{
        label: '男',
        value: '0'
      },
      {
        label: '女',
        value: '1'
      },
    ],
    genderVisible: false,
    genderValue: '',
    typeVisible: false,
    genderMap: ['', '男', '女'],
  },
  onGenderPicker() {
    this.setData({
      genderVisible: true
    })
  },
  onPickerChange(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;
    console.log('picker change:', e.detail);
    let text = value[0] == '0' ? '男' : '女'
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`${key}Text`]: text,
      'userInfo.gender': value
    });
  },
  onLoad() {
    this.init();
  },
  init() {
    const userInfo = wx.getStorageSync("userInfo");
    this.setData({
      userInfo: userInfo,
      genderText: userInfo.gender == 0 ? '男' : '女'
    })
    console.log('this.data.userInfo', this.data.userInfo)
    // this.getUserInfo();
  },
  getUserInfo() {
    let _this = this
    wx.cloud.callFunction({
      name: 'getUserInfo',
    }).then(res => {
      _this.setData({
        userInfo: res.result.data.data[0]
      })
      console.log('userInfo', _this.data.userInfo)
      wx.setStorageSync("userInfo", res.result.data.data[0])
    })
  },
  logout() {
    wx.showModal({
      title: '提示',
      content: '确认退出？',
      success(res) {
        if (res.confirm) {
          wx.removeStorageSync("userInfo")
          wx.switchTab({
            url: `/pages/me/index`,
          });
          app.globalData.login = false
          console.log('用户退出登陆')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  submit() {
    //校验信息是否按要求填写
    let msg = ''
    let phoneReg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    let _this = this
    let user = this.data.userInfo
    if (user.avatarurl == '') {
      msg = '请设置头像'
    } else if (user.nickname == '' || user.nickname.length > 20) {
      msg = '请正确填写昵称'
    } else if (user.gender == '') {
      msg = '请选择性别'
    } else if (!phoneReg.test(user.telnum)) {
      msg = '请输入正确的手机号'
      console.log('user.telnum:', user.telnum)
    }

    if (msg != '') {
      return Toast({
        context: this,
        selector: '#t-toast',
        message: msg,
        theme: 'error',
      });
    }

    if (this.data.avatarChange == 1) {
      this.fileUpload(this.data.userInfo.avatarurl)
    } else {
      _this.updateUserInfo()
    }
  },
  onGenderConfirm(e) {
    console.log(e.target)
  },
  telnumChange(e) {
    this.setData({
      'userInfo.telnum': e.detail.value
    })
  },
  nicknameChange(e) {
    this.setData({
      'userInfo.nickname': e.detail.value
    })
  },
  updateUserInfo() {
    let _this = this
    console.log('用户更新操作的数据：', this.data.userInfo)

    wx.cloud.callFunction({
      name: 'updateUserInfo',
      data: {
        avatarurl: _this.data.userInfo.avatarurl,
        gender: _this.data.userInfo.gender,
        nickname: _this.data.userInfo.nickname,
        telnum: _this.data.userInfo.telnum
      }
    }).then(res => {
      console.log('更新用户信息成功==>', res)
      wx.setStorageSync("userInfo", _this.data.userInfo)

      wx.cloud.callFunction({
        name: 'getUserInfo',
      }).then(res => {
        console.log('更新后===>', res.result.data.data[0])

      })
    }).catch(err => {
      console.error(err)
    })

    // TODO
    setTimeout(() => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: `更新成功`,
        theme: 'success',
      });
    }, 1000)
  },
  fileUpload(tempFilePath) {
    let cloudPath = 'img/' + new Date(Date.now()).toLocaleDateString().replace(/\s|\//g, '-') + '/' + util.wxuuid() + '.jpg'
    console.log('尝试上传图片：', tempFilePath, cloudPath)
    wx.cloud.init({
      env: 'time-companion-cloud-7be17d583f6'
    })
    wx.cloud.uploadFile({
      cloudPath: cloudPath,
      filePath: tempFilePath,
      success: res => {
        console.log("成功", res);
        wx.cloud.getTempFileURL({
          fileList: [res.fileID],
          success: res => {
            console.log(res, '临时链接')
            _this.setData({
              'userInfo.avatarurl': res.fileList[0].tempFileURL,
              'avatarChange': 0
            })
            _this.updateUserInfo()
          },
          fail(err) {
            console.log(err)
          }
        })
      },
      fail(err) {
        console.log('上传图片失败', err)
      }
    })
  },
  goAddress(){
    wx.navigateTo({
      url: '/pages/me/address/list/index',
    })
  },
  async toModifyAvatar() {
    let _this = this
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              path,
              size
            } = res.tempFiles[0];
            if (size <= 10485760) {
              resolve(path);
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传'
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      const tempUrlArr = tempFilePath.split('/');
      const tempFileName = tempUrlArr[tempUrlArr.length - 1];
      Toast({
        context: this,
        selector: '#t-toast',
        message: `已选择图片-${tempFileName}`,
        theme: 'success',
      });
      console.log('时间：' + new Date(Date.now()).toLocaleDateString().replace(/\s|\//g, '-'))
      _this.setData({
        'userInfo.avatarurl': tempFilePath,
        avatarChange: 1
      })
      wx.setStorageSync("userInfo", this.data.userInfo)
      console.log(tempFilePath)
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '修改头像出错了',
        theme: 'error',
      });

    }
  },


});